package cn.tpshion.vm.handler.task;

import cn.tpshion.vm.common.constant.BaseConstant;
import cn.tpshion.vm.common.constant.MsgType;
import cn.tpshion.vm.common.constant.NodeType;
import cn.tpshion.vm.common.constant.SecretType;
import cn.tpshion.vm.common.utils.AssertUtil;
import cn.tpshion.vm.domain.entity.Secret;
import cn.tpshion.vm.domain.support.DockerData;
import cn.tpshion.vm.domain.support.MsgData;
import cn.tpshion.vm.domain.support.NodeContext;
import cn.tpshion.vm.handler.task.support.AbstractNodeHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.io.File;

@Slf4j
@Component
public class DockerHandler extends AbstractNodeHandler<DockerData> {

    @Override
    public NodeType getNodeType() {
        return NodeType.DOCKER;
    }

    @Override
    protected void handleNode(NodeContext context) throws Exception {
        DockerData data = getData(context);

        String workspace = StringUtils.isBlank(data.getWorkDir()) ?
                context.getWorkspace() : context.getWorkspace() + File.separator + data.getWorkDir();

        String dockerFile = getDockerFile(workspace, data);
        String tag = StringUtils.isBlank(data.getRegistry()) ? data.getName() : data.getRegistry() + "/" + data.getName();

        String dockerBuildCmd = String.format("docker build -t %s:%s -f %s %s", tag, data.getVersion(), dockerFile, data.getBuildPath());
        int exitCode = localCommandHandler.exec(dockerBuildCmd, workspace, context);
        AssertUtil.isTrue(exitCode != 0, "构建镜像失败");

        if(StringUtils.isNoneBlank(data.getSecretName())){
            // 推送远程镜像
            Secret secret = getSecret(SecretType.DOCKER.getType(), data.getSecretName());
            String loginCmd = String.format("docker login -u %s -p %s %s", secret.getSecretKey(), secret.getSecretValue(), data.getRegistry());
            String pushCmd = String.format("docker push %s:%s", tag, data.getVersion());
            sseHandle.sendMessage(context, MsgData.of(MsgType.INFO, String.format("开始推送镜像 %s:%s", tag, data.getVersion())));
            int execCode = localCommandHandler.exec(loginCmd + " && " + pushCmd, context);
            AssertUtil.isTrue(execCode != 0, "推送镜像失败");
        }

        if(StringUtils.isNoneBlank(data.getAfterCmd())){
            localCommandHandler.exec(data.getAfterCmd(), workspace, context);
        }
    }

    private String getDockerFile(String workspace, DockerData data){
        String dockerFile = data.getDockerFile();
        if(StringUtils.isBlank(dockerFile)){
            return BaseConstant.DOCKERFILE;
        }
        return dockerFile.contains(BaseConstant.ENV_WORKSPACE) ? dockerFile.replaceAll(BaseConstant.ENV_WORKSPACE, workspace) : dockerFile;
    }
}
